<template>
  <div class="flex">
    <div class="form-control">
      <input type="file" ref="imgInput" accept="image/*" @change="handleImgChange" class="hidden"/>
      <label class="label">
        <button class="btn btn-neutral btn-outline btn-sm"
                @click="triggerImgUpload">上传图片
        </button>
      </label>
      <div class="w-full h-4"></div>
      <div class="flex h-28 w-8/12" v-if="modelValue">
        <div class="avatar cursor-pointer" @click="deleteImg()">
          <div class="w-auto h-28 rounded rounded-xl">
            <img :src="genFileUrl(modelValue)"/>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import {notificationError, notificationSuccess} from "~/utils/notification/index.js";
import {postForm, genFileUrl} from "~/utils/http/http-helper.js";

const props = defineProps({
  modelValue: String,
})

const emit = defineEmits(['update:modelValue'])

const imgInput = ref()
/**
 * 弹出文件选择框
 */
function triggerImgUpload() {
  imgInput.value.click(); // 模拟用户点击文件输入
}
// 处理文件改变
function handleImgChange(event) {
  console.log('files----')
  console.log(event.target.files)
  console.log('files----')
  const file = event.target.files[0]; // 获取文件
  if (file) {
    // 执行文件上传操作
    uploadImg(file);
  }
}
// 上传文件的方法
function uploadImg(file) {
  // 这里可以添加上传文件的逻辑，比如使用 FormData 发送请求等
  console.log('Uploading img...', file);
  // 上传文件的代码...
  const formData = new FormData();
  const filename = file.name
  if (!filename.endsWith(".png")
      && !filename.endsWith(".PNG")
      && !filename.endsWith(".jpg")
      && !filename.endsWith(".JPG")
      && !filename.endsWith(".jpeg")
      && !filename.endsWith(".JPEG")) {
    notificationError('请上传图片')
    return
  }
  formData.append('file', file);
  postForm('/api/files', formData).then(resp => {
    if (resp.success) {
      const data = resp.data
      const uploadImgRet = {}
      uploadImgRet.key = data.compressKey
      uploadImgRet.url = data.compressLocation
      emit('update:modelValue', uploadImgRet.key)
      console.log('上传文件...')
      console.log(data)
      console.log('上传文件...')

      notificationSuccess('上传图片成功')
    }
  }).catch(err => {
    console.log('err -> ' + err)
    notificationError(err)
  })
}
function deleteImg(){
  emit('update:modelValue', '')
}
</script>

<style scoped>

</style>